import 'dart:convert';
import 'dart:core';

// 宝宝基本信息
class BabyInfo {
  int? id;
  final int userId;
  final String name;
  final DateTime dateOfBirth;
  final String gender;
  final String bloodType;
  final double birthWeight;
  final double birthHeight;
  final String deliveryMethod;
  final String notes;
  final DateTime createdAt;
  final DateTime updatedAt;

  BabyInfo({
    this.id,
    required this.userId,
    required this.name,
    required this.dateOfBirth,
    required this.gender,
    this.bloodType = '',
    required this.birthWeight,
    required this.birthHeight,
    this.deliveryMethod = '',
    this.notes = '',
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 计算年龄
  String get age {
    final now = DateTime.now();
    final ageDuration = now.difference(dateOfBirth);
    final months = (ageDuration.inDays / 30.44).floor();
    final years = months ~/ 12;
    final remainingMonths = months % 12;

    if (years > 0) {
      return '$years岁$remainingMonths个月';
    } else {
      return '$months个月';
    }
  }

  // 计算月龄
  int get ageInMonths {
    final now = DateTime.now();
    return (now.difference(dateOfBirth).inDays / 30.44).floor();
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'name': name,
      'date_of_birth': dateOfBirth.toIso8601String(),
      'gender': gender,
      'blood_type': bloodType,
      'birth_weight': birthWeight,
      'birth_height': birthHeight,
      'delivery_method': deliveryMethod,
      'notes': notes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory BabyInfo.fromMap(Map<String, dynamic> map) {
    return BabyInfo(
      id: map['id'],
      userId: map['user_id'],
      name: map['name'],
      dateOfBirth: DateTime.parse(map['date_of_birth']),
      gender: map['gender'],
      bloodType: map['blood_type'] ?? '',
      birthWeight: map['birth_weight'],
      birthHeight: map['birth_height'],
      deliveryMethod: map['delivery_method'] ?? '',
      notes: map['notes'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  BabyInfo copyWith({
    int? id,
    int? userId,
    String? name,
    DateTime? dateOfBirth,
    String? gender,
    String? bloodType,
    double? birthWeight,
    double? birthHeight,
    String? deliveryMethod,
    String? notes,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return BabyInfo(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      name: name ?? this.name,
      dateOfBirth: dateOfBirth ?? this.dateOfBirth,
      gender: gender ?? this.gender,
      bloodType: bloodType ?? this.bloodType,
      birthWeight: birthWeight ?? this.birthWeight,
      birthHeight: birthHeight ?? this.birthHeight,
      deliveryMethod: deliveryMethod ?? this.deliveryMethod,
      notes: notes ?? this.notes,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// 宝宝成长记录（身高体重）
class GrowthRecord {
  int? id;
  final int babyId;
  final DateTime date;
  final double weight; // 体重（kg）
  final double height; // 身高（cm）
  final double headCircumference; // 头围（cm）
  final String notes;
  final String recordedBy;
  final DateTime createdAt;

  GrowthRecord({
    this.id,
    required this.babyId,
    required this.date,
    required this.weight,
    required this.height,
    this.headCircumference = 0,
    this.notes = '',
    this.recordedBy = '',
    DateTime? createdAt,
  }) : createdAt = createdAt ?? DateTime.now();

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'date': date.toIso8601String(),
      'weight': weight,
      'height': height,
      'head_circumference': headCircumference,
      'notes': notes,
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory GrowthRecord.fromMap(Map<String, dynamic> map) {
    return GrowthRecord(
      id: map['id'],
      babyId: map['baby_id'],
      date: DateTime.parse(map['date']),
      weight: map['weight'],
      height: map['height'],
      headCircumference: map['head_circumference'] ?? 0,
      notes: map['notes'] ?? '',
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
    );
  }

  // 复制对象并更新属性
  GrowthRecord copyWith({
    int? id,
    int? babyId,
    DateTime? date,
    double? weight,
    double? height,
    double? headCircumference,
    String? notes,
    String? recordedBy,
    DateTime? createdAt,
  }) {
    return GrowthRecord(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      date: date ?? this.date,
      weight: weight ?? this.weight,
      height: height ?? this.height,
      headCircumference: headCircumference ?? this.headCircumference,
      notes: notes ?? this.notes,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
    );
  }
}

// 疫苗接种记录
class VaccineRecord {
  int? id;
  final int babyId;
  final String vaccineName;
  final String vaccineType;
  final DateTime vaccinationDate;
  final String dose;
  final String lotNumber;
  final String manufacturer;
  final String doctorName;
  final String hospitalName;
  final String reactions;
  final String notes;
  final DateTime nextDueDate;
  final String recordedBy;
  final DateTime createdAt;

  VaccineRecord({
    this.id,
    required this.babyId,
    required this.vaccineName,
    required this.vaccineType,
    required this.vaccinationDate,
    this.dose = '',
    this.lotNumber = '',
    this.manufacturer = '',
    this.doctorName = '',
    this.hospitalName = '',
    this.reactions = '',
    this.notes = '',
    DateTime? nextDueDate,
    this.recordedBy = '',
    DateTime? createdAt,
  })  : nextDueDate = nextDueDate ?? DateTime.now(),
        createdAt = createdAt ?? DateTime.now();

  // 计算是否逾期
  bool get isOverdue {
    return nextDueDate.isBefore(DateTime.now());
  }

  // 计算距离下次接种还有多少天
  int get daysUntilNextDose {
    final now = DateTime.now();
    if (nextDueDate.isBefore(now)) {
      return -now.difference(nextDueDate).inDays;
    }
    return nextDueDate.difference(now).inDays;
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'vaccine_name': vaccineName,
      'vaccine_type': vaccineType,
      'vaccination_date': vaccinationDate.toIso8601String(),
      'dose': dose,
      'lot_number': lotNumber,
      'manufacturer': manufacturer,
      'doctor_name': doctorName,
      'hospital_name': hospitalName,
      'reactions': reactions,
      'notes': notes,
      'next_due_date': nextDueDate.toIso8601String(),
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory VaccineRecord.fromMap(Map<String, dynamic> map) {
    return VaccineRecord(
      id: map['id'],
      babyId: map['baby_id'],
      vaccineName: map['vaccine_name'],
      vaccineType: map['vaccine_type'],
      vaccinationDate: DateTime.parse(map['vaccination_date']),
      dose: map['dose'] ?? '',
      lotNumber: map['lot_number'] ?? '',
      manufacturer: map['manufacturer'] ?? '',
      doctorName: map['doctor_name'] ?? '',
      hospitalName: map['hospital_name'] ?? '',
      reactions: map['reactions'] ?? '',
      notes: map['notes'] ?? '',
      nextDueDate: DateTime.parse(map['next_due_date']),
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
    );
  }

  // 复制对象并更新属性
  VaccineRecord copyWith({
    int? id,
    int? babyId,
    String? vaccineName,
    String? vaccineType,
    DateTime? vaccinationDate,
    String? dose,
    String? lotNumber,
    String? manufacturer,
    String? doctorName,
    String? hospitalName,
    String? reactions,
    String? notes,
    DateTime? nextDueDate,
    String? recordedBy,
    DateTime? createdAt,
  }) {
    return VaccineRecord(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      vaccineName: vaccineName ?? this.vaccineName,
      vaccineType: vaccineType ?? this.vaccineType,
      vaccinationDate: vaccinationDate ?? this.vaccinationDate,
      dose: dose ?? this.dose,
      lotNumber: lotNumber ?? this.lotNumber,
      manufacturer: manufacturer ?? this.manufacturer,
      doctorName: doctorName ?? this.doctorName,
      hospitalName: hospitalName ?? this.hospitalName,
      reactions: reactions ?? this.reactions,
      notes: notes ?? this.notes,
      nextDueDate: nextDueDate ?? this.nextDueDate,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
    );
  }
}

// 疫苗接种计划
class VaccineSchedule {
  int? id;
  final int babyId;
  final String vaccineName;
  final String vaccineType;
  final String recommendedAge;
  final DateTime dueDate;
  final String description;
  final String importance;
  final String sideEffects;
  final String contraindications;
  final String notes;
  final bool isCompleted;
  final DateTime createdAt;
  final DateTime updatedAt;

  VaccineSchedule({
    this.id,
    required this.babyId,
    required this.vaccineName,
    required this.vaccineType,
    required this.recommendedAge,
    required this.dueDate,
    this.description = '',
    this.importance = '',
    this.sideEffects = '',
    this.contraindications = '',
    this.notes = '',
    this.isCompleted = false,
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 计算是否逾期
  bool get isOverdue {
    return dueDate.isBefore(DateTime.now()) && !isCompleted;
  }

  // 计算是否即将到期（7天内）
  bool get isUpcoming {
    final now = DateTime.now();
    final difference = dueDate.difference(now).inDays;
    return difference >= 0 && difference <= 7 && !isCompleted;
  }

  // 计算距离接种还有多少天
  int get daysUntilDue {
    final now = DateTime.now();
    if (dueDate.isBefore(now)) {
      return -now.difference(dueDate).inDays;
    }
    return dueDate.difference(now).inDays;
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'vaccine_name': vaccineName,
      'vaccine_type': vaccineType,
      'recommended_age': recommendedAge,
      'due_date': dueDate.toIso8601String(),
      'description': description,
      'importance': importance,
      'side_effects': sideEffects,
      'contraindications': contraindications,
      'notes': notes,
      'is_completed': isCompleted ? 1 : 0,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory VaccineSchedule.fromMap(Map<String, dynamic> map) {
    return VaccineSchedule(
      id: map['id'],
      babyId: map['baby_id'],
      vaccineName: map['vaccine_name'],
      vaccineType: map['vaccine_type'],
      recommendedAge: map['recommended_age'],
      dueDate: DateTime.parse(map['due_date']),
      description: map['description'] ?? '',
      importance: map['importance'] ?? '',
      sideEffects: map['side_effects'] ?? '',
      contraindications: map['contraindications'] ?? '',
      notes: map['notes'] ?? '',
      isCompleted: (map['is_completed'] ?? 0) == 1,
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  VaccineSchedule copyWith({
    int? id,
    int? babyId,
    String? vaccineName,
    String? vaccineType,
    String? recommendedAge,
    DateTime? dueDate,
    String? description,
    String? importance,
    String? sideEffects,
    String? contraindications,
    String? notes,
    bool? isCompleted,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return VaccineSchedule(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      vaccineName: vaccineName ?? this.vaccineName,
      vaccineType: vaccineType ?? this.vaccineType,
      recommendedAge: recommendedAge ?? this.recommendedAge,
      dueDate: dueDate ?? this.dueDate,
      description: description ?? this.description,
      importance: importance ?? this.importance,
      sideEffects: sideEffects ?? this.sideEffects,
      contraindications: contraindications ?? this.contraindications,
      notes: notes ?? this.notes,
      isCompleted: isCompleted ?? this.isCompleted,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// 喂养记录
class FeedingRecord {
  int? id;
  final int babyId;
  final DateTime timestamp;
  final String feedingType; // 'breastfeeding', 'bottle_milk', 'solid_food'
  final String side; // 'left', 'right', 'both' (仅适用于母乳喂养)
  final double amount; // 毫升或克
  final double duration; // 分钟
  final String foodName; // 固体食物名称
  final String notes;
  final String recordedBy;
  final DateTime createdAt;

  FeedingRecord({
    this.id,
    required this.babyId,
    required this.timestamp,
    required this.feedingType,
    this.side = '',
    this.amount = 0,
    this.duration = 0,
    this.foodName = '',
    this.notes = '',
    this.recordedBy = '',
    DateTime? createdAt,
  }) : createdAt = createdAt ?? DateTime.now();

  // 获取喂养类型的中文描述
  String get feedingTypeLabel {
    switch (feedingType) {
      case 'breastfeeding':
        return '母乳喂养';
      case 'bottle_milk':
        return '奶瓶喂养';
      case 'solid_food':
        return '固体食物';
      default:
        return '其他';
    }
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'timestamp': timestamp.toIso8601String(),
      'feeding_type': feedingType,
      'side': side,
      'amount': amount,
      'duration': duration,
      'food_name': foodName,
      'notes': notes,
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory FeedingRecord.fromMap(Map<String, dynamic> map) {
    return FeedingRecord(
      id: map['id'],
      babyId: map['baby_id'],
      timestamp: DateTime.parse(map['timestamp']),
      feedingType: map['feeding_type'],
      side: map['side'] ?? '',
      amount: map['amount'] ?? 0,
      duration: map['duration'] ?? 0,
      foodName: map['food_name'] ?? '',
      notes: map['notes'] ?? '',
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
    );
  }

  // 复制对象并更新属性
  FeedingRecord copyWith({
    int? id,
    int? babyId,
    DateTime? timestamp,
    String? feedingType,
    String? side,
    double? amount,
    double? duration,
    String? foodName,
    String? notes,
    String? recordedBy,
    DateTime? createdAt,
  }) {
    return FeedingRecord(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      timestamp: timestamp ?? this.timestamp,
      feedingType: feedingType ?? this.feedingType,
      side: side ?? this.side,
      amount: amount ?? this.amount,
      duration: duration ?? this.duration,
      foodName: foodName ?? this.foodName,
      notes: notes ?? this.notes,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
    );
  }
}

// 睡眠记录
class SleepRecord {
  int? id;
  final int babyId;
  final DateTime startTime;
  final DateTime endTime;
  final String sleepType; // 'nap', 'night'
  final double duration; // 小时
  final String notes;
  final String recordedBy;
  final DateTime createdAt;

  SleepRecord({
    this.id,
    required this.babyId,
    required this.startTime,
    required this.endTime,
    required this.sleepType,
    double? duration,
    this.notes = '',
    this.recordedBy = '',
    DateTime? createdAt,
  })  : duration = duration ?? endTime.difference(startTime).inMinutes / 60.0,
        createdAt = createdAt ?? DateTime.now();

  // 获取睡眠类型的中文描述
  String get sleepTypeLabel {
    switch (sleepType) {
      case 'nap':
        return '小睡';
      case 'night':
        return '夜间睡眠';
      default:
        return '其他';
    }
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'start_time': startTime.toIso8601String(),
      'end_time': endTime.toIso8601String(),
      'sleep_type': sleepType,
      'duration': duration,
      'notes': notes,
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory SleepRecord.fromMap(Map<String, dynamic> map) {
    return SleepRecord(
      id: map['id'],
      babyId: map['baby_id'],
      startTime: DateTime.parse(map['start_time']),
      endTime: DateTime.parse(map['end_time']),
      sleepType: map['sleep_type'],
      duration: map['duration'],
      notes: map['notes'] ?? '',
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
    );
  }

  // 复制对象并更新属性
  SleepRecord copyWith({
    int? id,
    int? babyId,
    DateTime? startTime,
    DateTime? endTime,
    String? sleepType,
    double? duration,
    String? notes,
    String? recordedBy,
    DateTime? createdAt,
  }) {
    return SleepRecord(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      startTime: startTime ?? this.startTime,
      endTime: endTime ?? this.endTime,
      sleepType: sleepType ?? this.sleepType,
      duration: duration ?? (endTime ?? this.endTime).difference(startTime ?? this.startTime).inMinutes / 60.0,
      notes: notes ?? this.notes,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
    );
  }
}

// 尿布记录
class DiaperRecord {
  int? id;
  final int babyId;
  final DateTime timestamp;
  final String type; // 'wet', 'dirty', 'both'
  final String consistency; // 'solid', 'loose', 'watery'
  final String color;
  final String notes;
  final String recordedBy;
  final DateTime createdAt;

  DiaperRecord({
    this.id,
    required this.babyId,
    required this.timestamp,
    required this.type,
    this.consistency = '',
    this.color = '',
    this.notes = '',
    this.recordedBy = '',
    DateTime? createdAt,
  }) : createdAt = createdAt ?? DateTime.now();

  // 获取尿布类型的中文描述
  String get typeLabel {
    switch (type) {
      case 'wet':
        return '尿湿';
      case 'dirty':
        return '便便';
      case 'both':
        return '尿湿+便便';
      default:
        return '其他';
    }
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'timestamp': timestamp.toIso8601String(),
      'type': type,
      'consistency': consistency,
      'color': color,
      'notes': notes,
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory DiaperRecord.fromMap(Map<String, dynamic> map) {
    return DiaperRecord(
      id: map['id'],
      babyId: map['baby_id'],
      timestamp: DateTime.parse(map['timestamp']),
      type: map['type'],
      consistency: map['consistency'] ?? '',
      color: map['color'] ?? '',
      notes: map['notes'] ?? '',
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
    );
  }

  // 复制对象并更新属性
  DiaperRecord copyWith({
    int? id,
    int? babyId,
    DateTime? timestamp,
    String? type,
    String? consistency,
    String? color,
    String? notes,
    String? recordedBy,
    DateTime? createdAt,
  }) {
    return DiaperRecord(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      timestamp: timestamp ?? this.timestamp,
      type: type ?? this.type,
      consistency: consistency ?? this.consistency,
      color: color ?? this.color,
      notes: notes ?? this.notes,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
    );
  }
}

// 早教方案
class EarlyEducationPlan {
  int? id;
  final int babyId;
  final String title;
  final String description;
  final String targetAgeRange; // '0-3m', '4-6m', '7-12m', '1-2y', '2-3y'
  final String category; // 'motor_skills', 'language', 'cognitive', 'social_emotional'
  final String activityType;
  final String instructions;
  final String materialsNeeded;
  final String benefits;
  final String tips;
  final String difficultyLevel; // 'easy', 'medium', 'hard'
  final int durationMinutes;
  final bool isFavorite;
  final DateTime createdAt;
  final DateTime updatedAt;

  EarlyEducationPlan({
    this.id,
    required this.babyId,
    required this.title,
    required this.description,
    required this.targetAgeRange,
    required this.category,
    required this.activityType,
    required this.instructions,
    this.materialsNeeded = '',
    this.benefits = '',
    this.tips = '',
    this.difficultyLevel = 'easy',
    this.durationMinutes = 15,
    this.isFavorite = false,
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 获取目标年龄段的中文描述
  String get targetAgeRangeLabel {
    switch (targetAgeRange) {
      case '0-3m':
        return '0-3个月';
      case '4-6m':
        return '4-6个月';
      case '7-12m':
        return '7-12个月';
      case '1-2y':
        return '1-2岁';
      case '2-3y':
        return '2-3岁';
      default:
        return '其他';
    }
  }

  // 获取类别的中文描述
  String get categoryLabel {
    switch (category) {
      case 'motor_skills':
        return '运动技能';
      case 'language':
        return '语言发展';
      case 'cognitive':
        return '认知发展';
      case 'social_emotional':
        return '社交情感';
      default:
        return '其他';
    }
  }

  // 获取难度级别的中文描述
  String get difficultyLevelLabel {
    switch (difficultyLevel) {
      case 'easy':
        return '简单';
      case 'medium':
        return '中等';
      case 'hard':
        return '困难';
      default:
        return '未知';
    }
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'title': title,
      'description': description,
      'target_age_range': targetAgeRange,
      'category': category,
      'activity_type': activityType,
      'instructions': instructions,
      'materials_needed': materialsNeeded,
      'benefits': benefits,
      'tips': tips,
      'difficulty_level': difficultyLevel,
      'duration_minutes': durationMinutes,
      'is_favorite': isFavorite ? 1 : 0,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory EarlyEducationPlan.fromMap(Map<String, dynamic> map) {
    return EarlyEducationPlan(
      id: map['id'],
      babyId: map['baby_id'],
      title: map['title'],
      description: map['description'],
      targetAgeRange: map['target_age_range'],
      category: map['category'],
      activityType: map['activity_type'],
      instructions: map['instructions'],
      materialsNeeded: map['materials_needed'] ?? '',
      benefits: map['benefits'] ?? '',
      tips: map['tips'] ?? '',
      difficultyLevel: map['difficulty_level'] ?? 'easy',
      durationMinutes: map['duration_minutes'] ?? 15,
      isFavorite: (map['is_favorite'] ?? 0) == 1,
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  EarlyEducationPlan copyWith({
    int? id,
    int? babyId,
    String? title,
    String? description,
    String? targetAgeRange,
    String? category,
    String? activityType,
    String? instructions,
    String? materialsNeeded,
    String? benefits,
    String? tips,
    String? difficultyLevel,
    int? durationMinutes,
    bool? isFavorite,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return EarlyEducationPlan(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      title: title ?? this.title,
      description: description ?? this.description,
      targetAgeRange: targetAgeRange ?? this.targetAgeRange,
      category: category ?? this.category,
      activityType: activityType ?? this.activityType,
      instructions: instructions ?? this.instructions,
      materialsNeeded: materialsNeeded ?? this.materialsNeeded,
      benefits: benefits ?? this.benefits,
      tips: tips ?? this.tips,
      difficultyLevel: difficultyLevel ?? this.difficultyLevel,
      durationMinutes: durationMinutes ?? this.durationMinutes,
      isFavorite: isFavorite ?? this.isFavorite,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// 成长里程碑
class GrowthMilestone {
  int? id;
  final int babyId;
  final String milestoneName;
  final String category; // 'motor', 'cognitive', 'language', 'social'
  final String description;
  final DateTime achievedDate;
  final String notes;
  final String photoPath;
  final String recordedBy;
  final DateTime createdAt;
  final DateTime updatedAt;

  GrowthMilestone({
    this.id,
    required this.babyId,
    required this.milestoneName,
    required this.category,
    required this.description,
    required this.achievedDate,
    this.notes = '',
    this.photoPath = '',
    this.recordedBy = '',
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 获取类别的中文描述
  String get categoryLabel {
    switch (category) {
      case 'motor':
        return '运动';
      case 'cognitive':
        return '认知';
      case 'language':
        return '语言';
      case 'social':
        return '社交';
      default:
        return '其他';
    }
  }

  // 计算实现里程碑时的月龄
  int ageInMonthsAtAchievement(BabyInfo babyInfo) {
    final duration = achievedDate.difference(babyInfo.dateOfBirth);
    return (duration.inDays / 30.44).floor();
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'milestone_name': milestoneName,
      'category': category,
      'description': description,
      'achieved_date': achievedDate.toIso8601String(),
      'notes': notes,
      'photo_path': photoPath,
      'recorded_by': recordedBy,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory GrowthMilestone.fromMap(Map<String, dynamic> map) {
    return GrowthMilestone(
      id: map['id'],
      babyId: map['baby_id'],
      milestoneName: map['milestone_name'],
      category: map['category'],
      description: map['description'],
      achievedDate: DateTime.parse(map['achieved_date']),
      notes: map['notes'] ?? '',
      photoPath: map['photo_path'] ?? '',
      recordedBy: map['recorded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  GrowthMilestone copyWith({
    int? id,
    int? babyId,
    String? milestoneName,
    String? category,
    String? description,
    DateTime? achievedDate,
    String? notes,
    String? photoPath,
    String? recordedBy,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return GrowthMilestone(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      milestoneName: milestoneName ?? this.milestoneName,
      category: category ?? this.category,
      description: description ?? this.description,
      achievedDate: achievedDate ?? this.achievedDate,
      notes: notes ?? this.notes,
      photoPath: photoPath ?? this.photoPath,
      recordedBy: recordedBy ?? this.recordedBy,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// 宝宝照片（云相册）
class BabyPhoto {
  int? id;
  final int babyId;
  final String photoPath;
  final DateTime captureDate;
  final String caption;
  final String location;
  final List<String> tags;
  final bool isFavorite;
  final String uploadedBy;
  final DateTime createdAt;
  final DateTime updatedAt;

  BabyPhoto({
    this.id,
    required this.babyId,
    required this.photoPath,
    required this.captureDate,
    this.caption = '',
    this.location = '',
    this.tags = const [],
    this.isFavorite = false,
    this.uploadedBy = '',
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 获取照片的月龄信息
  String ageInfo(BabyInfo babyInfo) {
    final duration = captureDate.difference(babyInfo.dateOfBirth);
    final months = (duration.inDays / 30.44).floor();
    return '$months个月';
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'photo_path': photoPath,
      'capture_date': captureDate.toIso8601String(),
      'caption': caption,
      'location': location,
      'tags': jsonEncode(tags),
      'is_favorite': isFavorite ? 1 : 0,
      'uploaded_by': uploadedBy,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory BabyPhoto.fromMap(Map<String, dynamic> map) {
    return BabyPhoto(
      id: map['id'],
      babyId: map['baby_id'],
      photoPath: map['photo_path'],
      captureDate: DateTime.parse(map['capture_date']),
      caption: map['caption'] ?? '',
      location: map['location'] ?? '',
      tags: map['tags'] != null ? List<String>.from(jsonDecode(map['tags'])) : [],
      isFavorite: (map['is_favorite'] ?? 0) == 1,
      uploadedBy: map['uploaded_by'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  BabyPhoto copyWith({
    int? id,
    int? babyId,
    String? photoPath,
    DateTime? captureDate,
    String? caption,
    String? location,
    List<String>? tags,
    bool? isFavorite,
    String? uploadedBy,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return BabyPhoto(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      photoPath: photoPath ?? this.photoPath,
      captureDate: captureDate ?? this.captureDate,
      caption: caption ?? this.caption,
      location: location ?? this.location,
      tags: tags ?? this.tags,
      isFavorite: isFavorite ?? this.isFavorite,
      uploadedBy: uploadedBy ?? this.uploadedBy,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// 成长发育评估结果
class DevelopmentAssessment {
  int? id;
  final int babyId;
  final DateTime assessmentDate;
  final String assessorName;
  final String assessorType; // 'doctor', 'parent', 'expert'
  final int overallScore;
  final Map<String, int> domainScores; // 各领域得分
  final String strengths;
  final String areasForImprovement;
  final String recommendations;
  final String notes;
  final DateTime createdAt;
  final DateTime updatedAt;

  DevelopmentAssessment({
    this.id,
    required this.babyId,
    required this.assessmentDate,
    required this.assessorName,
    required this.assessorType,
    required this.overallScore,
    this.domainScores = const {},
    this.strengths = '',
    this.areasForImprovement = '',
    this.recommendations = '',
    this.notes = '',
    DateTime? createdAt,
    DateTime? updatedAt,
  })  : createdAt = createdAt ?? DateTime.now(),
        updatedAt = updatedAt ?? DateTime.now();

  // 获取评估者类型的中文描述
  String get assessorTypeLabel {
    switch (assessorType) {
      case 'doctor':
        return '医生';
      case 'parent':
        return '家长';
      case 'expert':
        return '专家';
      default:
        return '其他';
    }
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'baby_id': babyId,
      'assessment_date': assessmentDate.toIso8601String(),
      'assessor_name': assessorName,
      'assessor_type': assessorType,
      'overall_score': overallScore,
      'domain_scores': jsonEncode(domainScores),
      'strengths': strengths,
      'areas_for_improvement': areasForImprovement,
      'recommendations': recommendations,
      'notes': notes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建对象
  factory DevelopmentAssessment.fromMap(Map<String, dynamic> map) {
    return DevelopmentAssessment(
      id: map['id'],
      babyId: map['baby_id'],
      assessmentDate: DateTime.parse(map['assessment_date']),
      assessorName: map['assessor_name'],
      assessorType: map['assessor_type'],
      overallScore: map['overall_score'],
      domainScores: map['domain_scores'] != null ? Map<String, int>.from(jsonDecode(map['domain_scores'])) : {},
      strengths: map['strengths'] ?? '',
      areasForImprovement: map['areas_for_improvement'] ?? '',
      recommendations: map['recommendations'] ?? '',
      notes: map['notes'] ?? '',
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制对象并更新属性
  DevelopmentAssessment copyWith({
    int? id,
    int? babyId,
    DateTime? assessmentDate,
    String? assessorName,
    String? assessorType,
    int? overallScore,
    Map<String, int>? domainScores,
    String? strengths,
    String? areasForImprovement,
    String? recommendations,
    String? notes,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return DevelopmentAssessment(
      id: id ?? this.id,
      babyId: babyId ?? this.babyId,
      assessmentDate: assessmentDate ?? this.assessmentDate,
      assessorName: assessorName ?? this.assessorName,
      assessorType: assessorType ?? this.assessorType,
      overallScore: overallScore ?? this.overallScore,
      domainScores: domainScores ?? this.domainScores,
      strengths: strengths ?? this.strengths,
      areasForImprovement: areasForImprovement ?? this.areasForImprovement,
      recommendations: recommendations ?? this.recommendations,
      notes: notes ?? this.notes,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? DateTime.now(),
    );
  }
}

// WHO生长标准数据类
class WHOGrowthStandard {
  final String ageRange; // 年龄段，如 '0-5m', '6-23m'
  final String gender; // 'male' 或 'female'
  final Map<String, double> weightPercentiles; // 体重百分位数据，如 {'p3': 3.0, 'p50': 5.0, 'p97': 7.0}
  final Map<String, double> heightPercentiles; // 身高百分位数据
  final Map<String, double> headCircumferencePercentiles; // 头围百分位数据

  WHOGrowthStandard({
    required this.ageRange,
    required this.gender,
    required this.weightPercentiles,
    required this.heightPercentiles,
    this.headCircumferencePercentiles = const {},
  });

  // 判断体重百分位
  String getWeightPercentileCategory(double weight) {
    if (weight < weightPercentiles['p3']!) return '体重过轻';
    if (weight < weightPercentiles['p15']!) return '体重偏轻';
    if (weight > weightPercentiles['p97']!) return '体重过重';
    if (weight > weightPercentiles['p85']!) return '体重偏重';
    return '体重正常';
  }

  // 判断身高百分位
  String getHeightPercentileCategory(double height) {
    if (height < heightPercentiles['p3']!) return '身高过矮';
    if (height < heightPercentiles['p15']!) return '身高偏矮';
    if (height > heightPercentiles['p97']!) return '身高过高';
    if (height > heightPercentiles['p85']!) return '身高偏高';
    return '身高正常';
  }

  // 将对象转换为Map
  Map<String, dynamic> toMap() {
    return {
      'age_range': ageRange,
      'gender': gender,
      'weight_percentiles': jsonEncode(weightPercentiles),
      'height_percentiles': jsonEncode(heightPercentiles),
      'head_circumference_percentiles': jsonEncode(headCircumferencePercentiles),
    };
  }

  // 从Map创建对象
  factory WHOGrowthStandard.fromMap(Map<String, dynamic> map) {
    return WHOGrowthStandard(
      ageRange: map['age_range'],
      gender: map['gender'],
      weightPercentiles: Map<String, double>.from(jsonDecode(map['weight_percentiles'])),
      heightPercentiles: Map<String, double>.from(jsonDecode(map['height_percentiles'])),
      headCircumferencePercentiles: Map<String, double>.from(jsonDecode(map['head_circumference_percentiles'])),
    );
  }
}